package service

import (
	"encoding/json"
	"errors"
	"gitee.com/gitee-go/core"
	"gitee.com/gitee-go/core/bean/oauthBean"
	"gitee.com/gitee-go/core/model/pipeline"
	"gitee.com/gitee-go/server/comm"
	"time"
)

// 查找数据库参数
func FindParam(key string) (*pipeline.TParam, bool) {
	e := &pipeline.TParam{}
	ok, err := comm.DBMain.GetDB().Where("name=?", key).Get(e)
	if err != nil {
		core.Log.Errorf("FindParam(%s) err:%v", key, err)
	}
	return e, ok
}

// 设置数据库参数
func SetParam(key string, data []byte, tit ...string) error {
	var err error
	db := comm.DBMain.GetDB()
	e, ok := FindParam(key)
	if len(tit) > 0 {
		e.Title = tit[0]
	}
	e.Data = string(data)
	if ok && e.Id > 0 { // 判断参数是否存在,存在就更新,不存在就新增
		_, err = db.Cols("title", "data").Where("id=?", e.Id).Update(e)
	} else {
		e.Name = key
		e.Times = time.Now()
		_, err = db.Insert(e)
	}
	return err
}

// 设置数据库参数(转json)
func SetsParam(key string, data interface{}, tit ...string) error {
	if data == nil {
		return errors.New("data is nil")
	}
	bts, err := json.Marshal(data)
	if err != nil {
		return err
	}
	return SetParam(key, bts, tit...)
}

// 获取数据库参数
func GetParam(key string) ([]byte, error) {
	e, ok := FindParam(key)
	if ok {
		return []byte(e.Data), nil
	}
	return nil, errors.New("not found param")
}

// 获取数据库参数(json转对象)
func GetsParam(key string, data interface{}) error {
	if data == nil {
		return errors.New("data is nil")
	}
	bts, err := GetParam(key)
	if err != nil {
		return err
	}
	return json.Unmarshal(bts, data)
}

// 获取通用参数(Oauth信息)
func GetsParamOAuthKey() (*oauthBean.ParamOAuth, error) {
	auth := &oauthBean.ParamOAuth{}
	return auth, GetsParam(oauthBean.ParamOAuthKey, auth)
}

// 获取数据库参数并缓存,减少数据库压力
func GetsParamCache(key string, data interface{}, outm ...time.Duration) error {
	err := comm.CacheGets(key, data)
	if err == nil {
		return nil
	}
	err = GetsParam(key, data)
	if err == nil {
		errs := comm.CacheSets(key, data, outm...)
		if errs != nil {
			core.Log.Errorf("GetsParamCache.CacheSets(%s) err:%v", key, errs)
		}
	}
	return err
}
